package com.sunny.ynhz.ui.index;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sunny.ynhz.R;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.ui.view.MyRefreshLayout;
import com.sunny.ynhz.utils.SPUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import io.rong.imkit.RongIM;

/**
 * Created by tangyunfei on 2017/9/1.
 */

public class ContactsFragment extends Fragment {
    private View rootView;
    private BaseAdapter mAdapter;
    private MyRefreshLayout myRefreshLayout;
    private ListView listView;
    private int page = 1;
    private String name = "";
    private String regionName = "";
    private String riverName = "";
    private RequestQueue mQueue;
    private ArrayList<HashMap<String,String>> datalist;
    private EditText keywordEdit;
    //private Button seacthBtn;
    private EditText riverEdit;
    private Button river_search_btn;
    private EditText areaEdit;
    //private Button area_search_btn;
    private String type="1";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mQueue = Volley.newRequestQueue(getActivity());
        if(rootView == null){
            rootView = inflater.inflate(R.layout.fragment_contacts,container,false);
            initView();
            loadData(name,regionName,riverName,type);
        }
        return  rootView;
    }

    private void loadData(String name,String regionName,String riverName,String type) {
        String url = "";
        if(type.equals("1"))
            url = NetUrl.baseUrl+"sysUserB/getMobleList?type="+type+"&name="+name+"&page="+page+"&userId="+SPUtil.get("userId","").toString();
        else if(type.equals("3"))
            url = NetUrl.baseUrl+"sysUserB/getMobleList?type="+type+"&regionName="+regionName+"&name="+name+"&page="+page+"&userId="+SPUtil.get("userId","").toString();
        else if(type.equals("2"))
            url = NetUrl.baseUrl+"sysUserB/getMobleList?type="+type+"&riverName="+riverName+"&regionName="+regionName+"&name="+name+"&page="+page+"&userId="+SPUtil.get("userId","").toString();;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if(status == 200){
                       // JSONObject data = jsonObject.getJSONObject("result");
                       JSONArray  data = jsonObject.getJSONArray("result");
                        Log.i("TAG","用户数量"+data.length());
                        for(int i=0;i<data.length();i++){
                           HashMap<String,String> hashMap = new HashMap<>();
                            JSONObject info = data.getJSONObject(i);
                            hashMap.put("id",info.getString("id"));
                            hashMap.put("name",info.getString("name"));
                            hashMap.put("phone",info.getString("mobile"));
                            datalist.add(hashMap);
                        }
                        mAdapter.notifyDataSetChanged();
                    }else{
                        if(page==1) {
                            Toast.makeText(getActivity(), "您搜索的用户不存在！", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getActivity(), "没有更多用户了！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    if(page == 1){
                         myRefreshLayout.setRefreshing(false);
                    }else{
                        myRefreshLayout.setLoading(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(page == 1){
                    myRefreshLayout.setRefreshing(false);
                }else{
                    myRefreshLayout.setLoading(false);
                }
            }
        });
        mQueue.add(stringRequest);

    }

    private void initView() {
        keywordEdit = (EditText)rootView.findViewById(R.id.keyword);
        //按行政区划搜索
        areaEdit = (EditText)rootView.findViewById(R.id.area_keyword);
        //按河涌名称搜索
        riverEdit = (EditText)rootView.findViewById(R.id.river_keyword);
        river_search_btn = (Button)rootView.findViewById(R.id.river_search_btn);
        river_search_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datalist.clear();

                name = keywordEdit.getText().toString();
                regionName = areaEdit.getText().toString();
                riverName = riverEdit.getText().toString();

                page =1;
                if(regionName.isEmpty() && riverName.isEmpty()) {
                    type="1";
                }else if(riverName.isEmpty()){
                    type="3";
                }else {
                    type = "2";
                }
                loadData(name,regionName,riverName,type);

            }
        });

         myRefreshLayout = rootView.findViewById(R.id.refresh);
         myRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
             @Override
             public void onRefresh() {
                 myRefreshLayout.postDelayed(new Runnable() {
                     @Override
                     public void run() {
                        page = 1;
                         datalist.clear();
                         loadData(name,regionName,riverName,type);
                     }
                 },1500);
             }
         });
        myRefreshLayout.setOnLoadListener(new MyRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                myRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                         page ++;
                        loadData(name,regionName,riverName,type);
                    }
                },1500);
            }
        });
        listView = (ListView)rootView.findViewById(R.id.listView);

        datalist = new ArrayList<>();
        mAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return datalist.size();
            }

            @Override
            public Object getItem(int i) {
                return i;
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View convertView, ViewGroup viewGroup) {
                 if(convertView == null){
                     convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_contacts,viewGroup,false);
                 }
                TextView title = (TextView)convertView.findViewById(R.id.id_name);
                title.setText(datalist.get(i).get("name"));

                TextView number =convertView.findViewById(R.id.id_number);
                 number.setText(datalist.get(i).get("phone"));
                 return  convertView;
            }
        };
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                RongIM.getInstance().startPrivateChat(getActivity(),
                        datalist.get(i).get("id"),
                        datalist.get(i).get("name"));
            }
        });
    }
}
